package com.financing.platform.web.api;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.financing.mail.dto.MailContentDTO;
import com.financing.mail.service.MailSenderService;
import com.financing.platform.common.Pager;
import com.financing.platform.common.ResultCode;
import com.financing.platform.common.ResultMap;
import com.financing.platform.common.BizEnums.BiddingReceiptEnums;
import com.financing.platform.common.ResultMap.STATUS;
import com.financing.platform.dto.FaNoticeDTO;
import com.financing.platform.dto.ForegroundProductDTO;
import com.financing.platform.dto.FpBiddingReceiptDTO;
import com.financing.platform.dto.FpProjectAnnualRevenue;
import com.financing.platform.dto.FpProjectRabate;
import com.financing.platform.dto.ProductSupplierDTO;
import com.financing.platform.dto.UserInfoDTO;
import com.financing.platform.service.IFaNoticeService;
import com.financing.platform.service.IForegroundProductService;
import com.financing.platform.service.IFpBiddingReceiptService;
import com.financing.platform.service.IProductSupplierService;
import com.financing.platform.service.IProjectService;
import com.financing.platform.util.CsvExportUtil;
import com.financing.platform.util.DTOdateSet;
import com.financing.platform.util.StringUtil;
import com.financing.platform.vo.ProjectSendConfirmEmailVO;

@Controller
@RequestMapping("/api/outProduct")
@Scope("prototype")
public class OutProductAction extends BaseAction {

	@Autowired
	private IProjectService projectServiceImpl;
	@Autowired
	private IForegroundProductService foregroundProductService;
	
	@Autowired
	private IProductSupplierService productSupplierService;

	@Autowired
	private MailSenderService mailSenderService;
	
	@Autowired
	private IFpBiddingReceiptService biddingReceiptService;
	
	@Autowired
	IFaNoticeService faNoticeService;
	/**
	 * 
	
	* @Title: queryForegroundProductList
	
	* @Description:查询用户产品供应列表
	
	* @param @param request
	* @param @param response
	* @param @return    设定文件
	
	* @return ResultMap    返回类型
	
	* @throws
	 */
	@RequestMapping("/queryForegroundProductList.shtml")
	@ResponseBody
	public ResultMap queryForegroundProductList(HttpServletRequest request,
			HttpServletResponse response, ForegroundProductDTO foregroundProductDto,Pager page) {
		try {
			log.info("In queryForegroundProductList add begin!");
			
			foregroundProductDto.setBegin(page.getStartIndex());
			foregroundProductDto.setEnd(page.getPageSize());
			int countForegroundProduct = foregroundProductService.countForegroundProduct(foregroundProductDto);
			page.setTotalCount(countForegroundProduct);
			List<ForegroundProductDTO> foregroundProductList = foregroundProductService.queryForegroundProduct(foregroundProductDto);
			resultMap.setAttribute("foregroundProductList", foregroundProductList);
			resultMap.setAttribute("pager", page);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		} catch (Exception e) {
			log.error("queryForegroundProductList add error !", e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		log.info("In queryForegroundProductList add end!");
		return resultMap;
	}
	
	
	/**
	 * 
	* @Title: queryForegroundProductDetail
	* @Description:查询用户产品供应详情
	* @param @param request
	* @param @param response
	* @param @return    设定文件
	* @return ResultMap    返回类型
	* @throws
	 */
	@RequestMapping("/queryForegroundProductDetail.shtml")
	@ResponseBody
	public ResultMap queryForegroundProductDetail(HttpServletRequest request,
			HttpServletResponse response, ForegroundProductDTO foregroundProductDto) {
		try {
			log.info("In queryForegroundProductDetail add begin!");
			
			if(StringUtils.isBlank(foregroundProductDto.getId())){
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_PARAMETERS_LOSE);
				return resultMap;
			}
			
			Map<String,Object> foregroundProductDetail = foregroundProductService.queryForegroundProductDetail(foregroundProductDto);
			if(foregroundProductDetail!=null&&!foregroundProductDetail.isEmpty()){
				resultMap.setAttribute("foregroundProductDetail", foregroundProductDetail);
				resultMap.setStatus(STATUS.SUCCESS);
				resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
			}else{
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_PRODUCT_NOTEXIST);
			}
		} catch (Exception e) {
			log.error("queryForegroundProductDetail add error !", e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		log.info("In queryForegroundProductDetail add end!");
		return resultMap;
	}
	
	/**
	 * @throws SQLException 
	 * 
	
	* @Title: queryForegroundProductList
	
	* @Description:给产品供应方发送邮件
	
	* @param @param request
	* @param @param response
	* @param @return    设定文件
	* @return ResultMap    返回类型
	
	* @throws
	 */
	@RequestMapping("/sendOutProductEmail.shtml")
	@ResponseBody
	public ResultMap sendOutProductEmail(HttpServletRequest request,
			HttpServletResponse response,String pids) throws SQLException {
		UserInfoDTO user = (UserInfoDTO) request.getSession().getAttribute(DTOdateSet.user);
		//判断参数为空
		if(StringUtil.isNullOrEmptyStr(pids)){
			log.info("sendConfirmEmail function : projectId is null");
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.STATUS_CODE_PARAMETERS_LOSE);
			return resultMap;
		}
		String[] ids = pids.split(",");
		List<Integer> pidList = new ArrayList<Integer>();
		for(String id : ids){
			pidList.add(Integer.parseInt(id));
		}
		//产品信息
		List<ProjectSendConfirmEmailVO> sendList = projectServiceImpl.queryOutProductInfoByIds(pidList.toArray(new Integer[]{}));
		// 获取邮件对象
		MailContentDTO mail = getEmailObject(sendList,user);
		boolean success=false;
		try {
			success = mailSenderService.send(mail);
		} catch (Exception e) {
			log.info("In send email error",e);
		}
		//否则执行成功
		if(success){
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		}else{
			resultMap.setMessage("邮件发送失败！");
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		return resultMap;
	}

	/**
	 * 
	
	* @Title: queryProductSupplierList
	
	* @Description:查询供应产品用户列表
	
	* @param @param request
	* @param @param response
	* @param @return    设定文件
	
	* @return ResultMap    返回类型
	
	* @throws
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/queryProductSupplierList.shtml")
	@ResponseBody
	public ResultMap queryProductSupplierList(HttpServletRequest request,
			HttpServletResponse response, ProductSupplierDTO productSupplierDto,Pager pager) {
		try {
			log.info("In queryProductSupplierList begin!");
			
			productSupplierDto.setBegin(pager.getStartIndex());
			productSupplierDto.setPageSize(pager.getPageSize());
			int count = productSupplierService.queryProductSupplierCount(productSupplierDto);
			pager.setTotalCount(count);
			
			List<ProductSupplierDTO> productSupplierList;
			if(count>0){
				productSupplierList = productSupplierService.queryProductSupplier(productSupplierDto);
			}else{
				productSupplierList = Collections.EMPTY_LIST;
			}
			resultMap.setAttribute("productSupplierList", productSupplierList);
			resultMap.setAttribute("pager", pager);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		} catch (Exception e) {
			log.error("queryProductSuppList add error !", e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		log.info("In queryProductSuppList add end!");
		return resultMap;
	}
	/**
	 * 
	
	* @Title: queryProductSupplierListCVS
	
	* @Description:查询供应产品用户列表  导出
	
	* @param @param request
	* @param @param response
	* @param @return    设定文件
	
	* @return ResultMap    返回类型
	
	* @throws
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping("/queryProductSupplierListCsv.shtml")
	public void queryProductSupplierListCsv(HttpServletRequest request,
			HttpServletResponse response, ProductSupplierDTO productSupplierDto) {
		try {
			productSupplierDto.setBegin(null);
			log.info("In queryProductSupplierListCsv begin!");
			List productSupplierList = productSupplierService.queryProductSupplier(productSupplierDto);
			CsvExportUtil.doCsvExport(response, productSupplierList);
		} catch (Exception e) {
			log.error("queryProductSupplierListCsv error !", e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		log.info("In queryProductSupplierListCsv end!");
		return ;
	}
	
	/**
	 * 
	
	* @Title: queryForegroundProductInfo
	
	* @Description:查询用户产品供应信息
	
	* @param @param request
	* @param @param response
	* @param @return    设定文件
	
	* @return ResultMap    返回类型
	
	* @throws
	 */
	@RequestMapping("/queryProductSupplierInfo.shtml")
	@ResponseBody
	public ResultMap queryProductSupplierInfo(HttpServletRequest request,
			HttpServletResponse response, ProductSupplierDTO productSupplierDto) {
		try {
			log.info("In queryForegroundProductInfo  begin!");
			
			productSupplierDto = productSupplierService.queryProductSupplierInfo(productSupplierDto);
			
			resultMap.setAttribute("bean", productSupplierDto);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		} catch (Exception e) {
			log.error("queryForegroundProductInfo error !", e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		log.info("In queryForegroundProductInfo end!");
		return resultMap;
	}
	/**
	 * 
	
	* @Title: editProductSupplier
	
	* @Description:编辑产品供应方信息
	
	* @param @param request
	* @param @param response
	* @param @return    设定文件
	
	* @return ResultMap    返回类型
	
	* @throws
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/saveProductSupplierInfo.shtml")
	@ResponseBody
	public ResultMap saveProductSupplierInfo(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			log.info("In editProductSupplier add begin!");
			ProductSupplierDTO productSupplierDto = new ProductSupplierDTO();
			DTOdateSet.setUpdateInfo(productSupplierDto, request.getSession());
			Map map =  getParameterMap(request);
			map.put("updateBy", productSupplierDto.getUpdateBy());
			map.put("updateDate", productSupplierDto.getUpdateDate());
			productSupplierService.editProductSupplier(map);
			
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		} catch (Exception e) {
			log.error("editProductSupplier add error !", e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		log.info("In editProductSupplier add end!");
		return resultMap;
	}
	
	/**
	 * 
	
	* @Title: editForegroundProduct
	
	* @Description:审核状态修改
	
	* @param @param request
	* @param @param response
	* @param @return    设定文件
	
	* @return ResultMap    返回类型
	
	* @throws
	 */
	@RequestMapping("/editForegroundProduct.shtml")
	@ResponseBody
	public ResultMap editForegroundProduct(HttpServletRequest request,
			HttpServletResponse response, ForegroundProductDTO foregroundProductDto) {
		try {
			log.info("In editForegroundProduct edit begin!");
			
			String productType = foregroundProductDto.getProductType();
			String id = foregroundProductDto.getId();
			String checkStatus = foregroundProductDto.getCheckStatus();
			if(StringUtils.isBlank(productType)||StringUtils.isBlank(id)||StringUtils.isBlank(checkStatus)){
				log.info("参数缺失!!!!");
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_PARAMETERS_LOSE);
				return resultMap;
			}
			String failReson = foregroundProductDto.getFailReson();
			if(("6".equals(checkStatus)||"3".equals(checkStatus))&&StringUtils.isBlank(failReson)){
				log.info("参数缺失!!!!");
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_PARAMETERS_LOSE);
				return resultMap;
			}
			
			ForegroundProductDTO foregroundProduct=new ForegroundProductDTO();
			foregroundProduct.setId(id);
			foregroundProduct.setProductType(productType);
			List<ForegroundProductDTO> foregroundProductList = foregroundProductService.queryForegroundProduct(foregroundProduct);
			if(foregroundProductList.size()==0){
				log.info("未有该产品！！！");
				resultMap.setStatus(STATUS.FAILE);
				resultMap.setStatusCode(ResultCode.STATUS_CODE_PARAMETERS_LOSE);
				return resultMap;
			}
			
			ForegroundProductDTO updateDto = foregroundProductList.get(0);
			updateDto.setCheckStatus(checkStatus);
			//审核失败，发布失败的话需要填写原因   
			String updateCheckStatus = updateDto.getCheckStatus();
			if("3".equals(updateCheckStatus)||"6".equals(updateCheckStatus)){
				updateDto.setFailReson(failReson);
			}
			//发布要已经发布
			if("5".equals(updateCheckStatus)||"4".equals(updateCheckStatus)){
				String productType2 = updateDto.getProductType();
				String updatepStatus = updateDto.getpStatus();
				boolean type="05".equals(productType2)?!"1".equals(updatepStatus):!"2".equals(updatepStatus);
				if(type){
					log.info("不符合此操作条件！！！");
					resultMap.setStatus(STATUS.FAILE);
					resultMap.setStatusCode(ResultCode.STATUS_CODE_NOT_PUBLISH);
					return resultMap;
				}
				if("wap".equals(updateDto.getProductSource())){//手机端上传产品 做自动承销
					//修改成产品已发布        承销 对应产品操作
					JSONArray json=new JSONArray();//竞价价格
					
					JSONArray currentRebate=null;
					if("1".equals(updateDto.getRebateType())){
						if(!updateDto.getRebateRate().contains("[")){//第二种类型   转jsonArray   区间返佣
							updateDto.setRebateRate("["+updateDto.getRebateRate()+"]");
						}
						currentRebate=JSONArray.fromObject(updateDto.getRebateRate());
					}
					
					//查询年化益率信息
					List<FpProjectRabate> productProfitRebateList = projectServiceImpl.getProductProfitRebateList(Integer.parseInt(updateDto.getpId()));
					if(productProfitRebateList.size()==0){
						resultMap.setStatus(STATUS.FAILE);
						resultMap.setStatusCode(ResultCode.STATUS_CODE_NULL_PROFITREBATE);
						return resultMap;
					}
					int num=0;
					for (FpProjectRabate fpProjectRabate : productProfitRebateList) {
						try {
							FpProjectAnnualRevenue annualRevenue = fpProjectRabate.getAnnualRevenue();//收益率  区间
							BigDecimal pRabateProfit=fpProjectRabate.getpRabateProfit();//官网返佣
							//协议价 直接不能竞价
							if("1".equals(fpProjectRabate.getpIsAgreement())){
								break;
							}
							if("2".equals(updateDto.getRebateType())){//比例返佣
								//竞价价格不能低于官网价格
								if(new BigDecimal(updateDto.getRebateRate()).compareTo(pRabateProfit)>=0){
									JSONObject a=new JSONObject();
									a.put("id", annualRevenue.getId());
									a.put("rebate",updateDto.getRebateRate());
									json.add(a);
									num++;
								}
							}else{//区间返佣
									BigDecimal pStartAmount = annualRevenue.getPStartAmount();
									BigDecimal pEndAmount = annualRevenue.getPEndAmount();
									for (int i = 0; i < currentRebate.size(); i++) {
										BigDecimal pStart=new BigDecimal(currentRebate.getJSONObject(i).get("rangeBegin")+"");
										pStart=pStart.multiply(new BigDecimal(10000));//加上万 格式
										BigDecimal pEnd=new BigDecimal(currentRebate.getJSONObject(i).get("rangeEnd")+"");
										pEnd=pEnd.multiply(new BigDecimal(10000));//加上万 格式
										if(!(pStart.compareTo(pStartAmount)==0&&pEnd.compareTo(pEndAmount)==0)){
											continue;
										}
										BigDecimal rate=new BigDecimal(""+currentRebate.getJSONObject(i).get("rate"));
										if(rate.compareTo(pRabateProfit)>=0){
											JSONObject a=new JSONObject();
											a.put("id", annualRevenue.getId());
											a.put("rebate",rate);
											json.add(a);
											num++;
										}
									}
							}
						} catch (Exception e) {
							log.error("editForegroundProduct.productProfitRebateList",e);
						}
					}
					if(num==productProfitRebateList.size()&&productProfitRebateList.size()>0){
						//承销成功
						log.info("承销中。。。。。");
						FpBiddingReceiptDTO fpBiddingReceiptDto=new FpBiddingReceiptDTO();//竞价
						fpBiddingReceiptDto.setSrouce("admin");
						fpBiddingReceiptDto.setFaId(updateDto.getFaId());
						fpBiddingReceiptDto.setpId(Integer.parseInt(updateDto.getpId()));
						fpBiddingReceiptDto.setpName(updateDto.getProductName());
						fpBiddingReceiptDto.setMobile(updateDto.getMobile());
						fpBiddingReceiptDto.setpType(productType2);
						fpBiddingReceiptDto.setFlagAnonymous(updateDto.getFlagAnonymous());
						DTOdateSet.setCreateInfo(fpBiddingReceiptDto, request.getSession());
						DTOdateSet.setUpdateInfo(fpBiddingReceiptDto, request.getSession());
						biddingReceiptService.addFpBiddingReceiptBatch(json, fpBiddingReceiptDto);
						log.info("承销结束。。。。。");
					}else{
						log.info("价格不满足承销条件,或者协议价不能竞价。。");
						//   是否需要发送消息
						FaNoticeDTO faNotice=new FaNoticeDTO();
						DTOdateSet.setCreateInfo(faNotice, request.getSession());
						DTOdateSet.setUpdateInfo(faNotice, request.getSession());
						faNotice.setType("09");//消息通知
						faNotice.setProductId(Integer.parseInt(updateDto.getpId()));
						faNotice.setProductType(productType2);
						faNotice.setSource("【SuperFA】");
						faNotice.setStatus("01");
						String s=String.format("您竞价的产品%s已审核成功，但出价低于官网价，未获取产品承销权，如有问题请拨打电话%s", updateDto.getProductName(),"400-855-8085");
						faNotice.setTitle("承销失败");
						faNotice.setContent(s);
						faNotice.setFaId(updateDto.getFaId());
						faNoticeService.addFaNotice(faNotice);
						
					}
				}
			}
			
			//审核通过   校验
			if("2".equals(updateCheckStatus)&&!"wap".equals(updateDto.getProductSource())){
				ProductSupplierDTO productSupplierDto=new ProductSupplierDTO();
				productSupplierDto.setFaId(updateDto.getFaId());
				List<ProductSupplierDTO> queryProductSupplier = productSupplierService.queryProductSupplier(productSupplierDto);
				//不存在供应方信息
				if(queryProductSupplier.size()==0){
					log.error("==>warn queryProductSupplier is empty ");
					resultMap.setStatus(STATUS.ERROR);
					resultMap.setStatusCode(ResultCode.STATUS_CODE_NOT_SUPPLIER);
				}			
				ProductSupplierDTO productSupplier = queryProductSupplier.get(0);
				//供应方为黑名单
				if("1".equals(productSupplier.getBlackList())){
					log.error("==>warn getBlackList is 1 ");
					resultMap.setStatus(STATUS.ERROR);
					resultMap.setStatusCode(ResultCode.STATUS_CODE_IS_BLACK);
				}
				//供应方审核未通过
				if(!"2".equals(productSupplier.getCheckStatus())&&!"4".equals(productSupplier.getCheckStatus())&&!"5".equals(productSupplier.getCheckStatus())){
					log.error("==>warn productSupplier.getCheckStatus() is no pass ");
					resultMap.setStatus(STATUS.ERROR);
					resultMap.setStatusCode(ResultCode.STATUS_CODE_NOT_CHECK);
					return resultMap;
				}
			}
			
			DTOdateSet.setUpdateInfo(updateDto, request.getSession());
			foregroundProductService.editForegroundProduct(updateDto);
			resultMap.setStatus(STATUS.SUCCESS);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SUCCESS);
		} catch (Exception e) {
			log.error("editForegroundProduct edit error !", e);
			resultMap.setStatus(STATUS.FAILE);
			resultMap.setStatusCode(ResultCode.RESULT_CODE_SYSTEM_ERROR);
		}
		
		log.info("In editForegroundProduct add end!");
		return resultMap;
	}
	
	/**
	 * 从request中获得参数Map，并返回可读的Map
	 * 
	 * @param request
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public  Map getParameterMap(HttpServletRequest request) {
	    // 参数Map
	    Map properties = request.getParameterMap();
	    // 返回值Map
	    Map returnMap = new HashMap();
	    Iterator entries = properties.entrySet().iterator();
	    Map.Entry entry;
	    String name = "";
	    String value = "";
	    while (entries.hasNext()) {
	        entry = (Map.Entry) entries.next();
	        name = (String) entry.getKey();
	        Object valueObj = entry.getValue();
	        if(null == valueObj){
	            value = "";
	        }else if(valueObj instanceof String[]){
	            String[] values = (String[])valueObj;
	            for(int i=0;i<values.length;i++){
	                value = values[i] + ",";
	            }
	            value = value.substring(0, value.length()-1);
	        }else{
	            value = valueObj.toString();
	        }
	        returnMap.put(name, value);
	    }
	    return returnMap;
	}
}
